<template>
  <div>
    <TopFilter ref="formpanel1" :list="formList1" @filterChange="formchangeFun" />
    <FilterTable
      ref="basetable"
      columnsRef="partPartOutboundPartBreakAddModal"
      :columns="columns"
      height="300"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :dataSource="datasourceTablefirst"
      :onEnterEvent="tableDbclickFun"
      selectionType="single"
      :onRowSelectChange="selectTableFun"
    ></FilterTable>
    <FormPanel ref="formpanel2" :list="formList2" labelWidth="100" :isSubmitBtn="false" @formChange="formchangeFuns" />
    <FilterTable
      ref="basetables"
      columnsRef="partPartOutboundPartBreakAddModal1"
      :isSelectColumn="false"
      :columns="columns1"
      :dataSource="datasourceTablesecond"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns1 => (this.columns1 = columns1)"
      height="300"
      :onSyncTableData="tablechangeFun"
    ></FilterTable>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9999,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">关 闭</el-button>
      <el-button type="primary" @click="confirmHandle">保 存</el-button>
    </div>
  </div>
</template>
<script>
import { queryPartItem, queryPartItemInfos, lackInventory, getStroageList, getbrandsdictList } from '@/api/part/partOutbound/partBreak';
import { dictionary } from '@/utils/dictMixin';
export default {
  mixins: [dictionary],
  props: ['lossNo'],
  data() {
    lossNo: this.lossNo, (this.basetable = null);
    this.basetables = null;
    return {
      formList1: this.createFrom(),
      formList2: this.createFroms(),
      fetchApi: queryPartItem,
      fetchParams: {
        xhrAbort: true,
        sort: '',
        order: 'asc',
        limit: '10',
        offset: '0',
        queryPart_table: '',
        dmsFuncId: '35100010',
        _: '1565683718279'
      },
      getutildata: {
        dmsFuncId: '35100010',
        _: '1565683718279'
      },
      columns: this.createTable(),
      columns1: this.createTables(),
      datasourceTablefirst: [],
      datasourceTablesecond: [],
      tablelistfirst: [],
      tablelistsecond: [],
      getpartParams: {
        sort: 'STORAGE_CODE',
        order: 'asc',
        limit: '10',
        offset: '0',
        queryPart_table: '',
        STORAGE_CODE: '',
        PART_NO: ''
      },
      fromSubmitdata: {}
    };
  },
  created() {},
  mounted() {
    this.initSelect();
    this.basetable = this.$refs.basetable.$refs.pageTable;
    this.basetables = this.$refs.basetables.$refs.pageTable;
  },
  methods: {
    async initSelect() {
      // 仓库
      this.formList2.find(item => item.fieldName === 'STORAGE_CODE').itemList = this.formList1[0].itemList = (await getStroageList()).data.map(x => ({ value: x.STORAGE_CODE, text: x.STORAGE_NAME }));
      // 品牌
      this.formList1[1].itemList = (await getbrandsdictList()).data.map(x => ({ value: x.brandCode, text: x.brandName }));
    },
    checkPriceRate(rule, value, callback) {
      let reg = /^([1-9])(\.\d{1,2})?$/;
      if (!reg.test(value)) {
        return callback(new Error(rule.message));
      }
      callback();
    },
    checkZero(rule, value, callback) {
      if (value <= rule.limit) {
        return callback(new Error(rule.message));
      }
      callback();
    },
    createFrom() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'storageCode',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '配件类别',
          fieldName: 'partGroupCode',
          itemList: this.createDictList('8075')
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo'
        },
        {
          type: 'INPUT',
          label: '拼音代码',
          fieldName: 'spellCode'
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName'
        },
        {
          type: 'INPUT',
          label: '库位',
          fieldName: 'storagePositionCode'
        },
        // {
        //   type: 'SELECT',
        //   label: '库存大于零',
        //   fieldName: 'stockOverZero',
        //   initialValue:10041001,
        //   itemList: [{ text: '是', value: 10041001 }]
        // },
        // {
        //   type: 'SELECT',
        //   label: '售价大于零',
        //   fieldName: 'priceOverZero',
        //   itemList: [{ text: '是', value: 10041001 }]
        // },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark'
        }
      ];
    },
    createTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '仓库代码',
        //   dataIndex: 'STORAGE_CODE',
        //   sorter: true,
        //   filter: true
        // },
        {
          title: '库位',
          dataIndex: 'STORAGE_POSITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售价',
          dataIndex: 'SALES_PRICE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '成本价',
          dataIndex: 'COST_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '可用库存',
          dataIndex: 'USEABLE_STOCK',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '账面库存',
          dataIndex: 'STOCK_QUANTITY',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        // {
        //   title: '借进数量',
        //   dataIndex: 'BORROW_QUANTITY',
        //   sorter: true,
        //   filter: true
        // },
        // {
        //   title: '借出数量',
        //   dataIndex: 'LEND_QUANTITY',
        //   sorter: true,
        //   filter: true
        // },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件类别',
          dataIndex: 'PART_GROUP_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.createDictText(props.row.PART_GROUP_CODE, '8075')}</span>;
          }
        }
      ];
    },
    createFroms() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'STORAGE_CODE',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'PART_NO',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'PART_NAME',
          rules: [{ required: true, message: '请输入配件名称', trigger: 'blur' }]
        },
        // {
        //   type: 'SELECT',
        //   label: '价格类型',
        //   fieldName: 'PRICE_TYPE',
        //   initialValue: 80501001,
        //   itemList: this.createDictList('8050'),
        //   change: val => {
        //     this.changeType(val);
        //   }
        // },
        // {
        //   type: 'INPUT_NUMBER',
        //   label: '价格系数',
        //   fieldName: 'PRICE_RATE',
        //   initialValue: 1,
        //   min: 0.01,
        //   max: 10,
        //   rules: [{ required: true, message: '请输入价格系数', trigger: 'blur' }, { limit: 0, validator: this.checkPriceRate, message: '0-10之间,保留两位小数!', trigger: 'blur' }],
        //   change: val => {
        //     this.changecoefficient(val);
        //   }
        // }
        {
          type: 'INPUT_NUMBER',
          label: '报损单价',
          fieldName: 'LOSS_PRICE',
          min: 0.01,
          precision: 2,
          rules: [{ required: true, message: '请输入报损单价', trigger: 'blur' }],
          change: val => {
            this.changePrice(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '报损数量',
          fieldName: 'LOSS_QUANTITY',
          initialValue: '1',
          precision: 2,
          rules: [
            { required: true, message: '请输入报损数量', trigger: 'blur' },
            { limit: 0, validator: this.checkZero, message: '报损数量不能为0', trigger: 'blur' }
          ],
          change: val => {
            this.changeNum(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '报损金额',
          fieldName: 'LOSS_AMOUNT',
          precision: 2,
          disabled: true
        }
      ];
    },
    createTables() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '销售价',
          dataIndex: 'SALES_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '索赔价',
          dataIndex: 'CLAIM_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '终端建议零售价格',
          dataIndex: 'INSURANCE_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        // {
        //   title: '最低销售限价',
        //   dataIndex: 'MIN_LIMIT_PRICE',
        //   sorter: true,
        //   filter: true
        // },
        {
          title: '销售限价',
          dataIndex: 'LIMIT_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '成本价',
          dataIndex: 'COST_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '网点价',
          dataIndex: 'NODE_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '最新进货价',
          dataIndex: 'LATEST_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '建议销售价',
          dataIndex: 'INSTRUCT_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '最大库存',
          dataIndex: 'MAX_STOCK',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '最小库存',
          dataIndex: 'MIN_STOCK',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '账面库存',
          dataIndex: 'STOCK_QUANTITY',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '可用库存',
          dataIndex: 'USEABLE_STOCK',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        // {
        //   title: '借进数量',
        //   dataIndex: 'BORROW_QUANTITY',
        //   sorter: true,
        //   filter: true
        // },
        // {
        //   title: '借出数量',
        //   dataIndex: 'LEND_QUANTITY',
        //   sorter: true,
        //   filter: true
        // },
        {
          title: '锁定量',
          dataIndex: 'LOCKED_QUANTITY',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '单位代码',
          dataIndex: 'UNIT_CODE',
          sorter: true,
          filter: true,
          hidden: true,
          filterType: 'input'
        },
        {
          title: '单位名称',
          dataIndex: 'UNIT_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    // 选中事件
    selectTableFun(val) {
      if (val && val.length > 0) {
      }
    },
    formchangeFun(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val, { xhrAbort: false });
    },
    formchangeFuns(val) {
      // debugger;
      console.log(val, 'formchangeFuns');
      this.fromSubmitdata = val; // {...val};
    },
    tableDbclickFun(val) {
      this.datasourceTablesecond = [];
      this.tablelistfirst = val;
      this.formList2.find(item => item.fieldName === 'STORAGE_CODE').initialValue = val.STORAGE_CODE;
      this.formList2.find(item => item.fieldName === 'PART_NO').initialValue = val.PART_NO;
      this.formList2.find(item => item.fieldName === 'PART_NAME').initialValue = val.PART_NAME;
      // this.formList2[3].initialValue = 80501001;
      // this.formList2[4].initialValue = 1.0;
      this.formList2.find(item => item.fieldName === 'LOSS_PRICE').initialValue = val.COST_PRICE.toFixed(2);
      this.formList2.find(item => item.fieldName === 'LOSS_QUANTITY').initialValue = 1.0;
      this.formList2.find(item => item.fieldName === 'LOSS_AMOUNT').initialValue = val.COST_PRICE.toFixed(2);
      this.getpartlist(val);
    },
    // 改变价格类型
    changeType(val) {
      let lossPrice = 0;
      if (this.tablelistsecond[0]) {
        // 成本价
        if (val == 80501001) {
          lossPrice = this.tablelistsecond[0].COST_PRICE;
        } else if (val == 80501002) {
          // 销售价
          lossPrice = this.tablelistsecond[0].SALES_PRICE;
        } else if (val == 80501003) {
          // 索赔价
          lossPrice = this.tablelistsecond[0].CLAIM_PRICE;
        } else if (val == 80501004) {
          // 网点价
          lossPrice = this.tablelistsecond[0].NODE_PRICE;
        } else if (val == 80501005) {
          // 最新进货价
          lossPrice = this.tablelistsecond[0].LATEST_PRICE;
        } else if (val == 80501006) {
          // 含税成本价
          lossPrice = 0;
        } else if (val == 80501007) {
          // 终端建议零售价格
          lossPrice = this.tablelistsecond[0].INSURANCE_PRICE;
        } else if (val == 80501008) {
          // 建议销售价
          lossPrice = this.tablelistsecond[0].INSTRUCT_PRICE;
        } else if (val == 80501009) {
          // 销售限价
          lossPrice = this.tablelistsecond[0].LIMIT_PRICE;
        }
      } else {
        lossPrice = 0;
      }

      // 单价系数
      // let priceRate = this.formList2[4].initialValue;
      // 报损数量
      const lossQuantity = this.formList2.find(item => item.fieldName === 'LOSS_QUANTITY').initialValue;
      // 报损单价
      this.formList2.find(item => item.fieldName === 'LOSS_PRICE').initialValue = lossPrice.toFixed(2);
      // 报损金额
      this.formList2.find(item => item.fieldName === 'LOSS_AMOUNT').initialValue = (lossPrice * lossQuantity).toFixed(2);
    },
    // 改变单价系数
    changecoefficient(val) {
      // 报损数量
      const lossQuantity = this.formList2.find(item => item.fieldName === 'LOSS_QUANTITY').initialValue;
      // 报损单价
      this.formList2.find(item => item.fieldName === 'LOSS_PRICE').initialValue = val * this.tablelistsecond[0].COST_PRICE.toFixed(2);
      // 报损金额
      this.formList2.find(item => item.fieldName === 'LOSS_AMOUNT').initialValue = (val * this.tablelistsecond[0].COST_PRICE * lossQuantity).toFixed(2);
    },
    // 改变报损单价
    changePrice(val) {
      // 单价系数
      // let priceRate = this.formList2[4].initialValue;
      // 报损数量
      const lossQuantity = this.formList2.find(item => item.fieldName === 'LOSS_QUANTITY').initialValue;
      this.formList2.find(item => item.fieldName === 'LOSS_AMOUNT').initialValue = (val * lossQuantity).toFixed(2);
    },
    // 改变数量
    changeNum(val) {
      // 单价系数
      // let priceRate = this.formList2[4].initialValue;
      // 报损单价
      let lossPrice = this.formList2.find(item => item.fieldName === 'LOSS_PRICE').initialValue.toFixed(2);
      this.formList2.find(item => item.fieldName === 'LOSS_AMOUNT').initialValue = (val * lossPrice).toFixed(2);
    },
    async getpartlist(val) {
      let res = await queryPartItemInfos({ partNo: val.PART_NO, storageCode: val.STORAGE_CODE });
      this.basetables.EXECUTE_INSERT(res.data.rows);
    },
    // 关闭弹窗
    closeDialog() {
      this.$emit('close', false);
    },
    tablechangeFun(val) {
      this.tablelistsecond = val;
    },
    // 添加事件提交表单
    async confirmHandle() {
      this.$refs.formpanel2.SUBMIT_FORM();
      if (!this.fromSubmitdata.LOSS_AMOUNT) {
        return;
      }
      if (!this.tablelistsecond[0]) {
        return this.$notify.error({ title: '提示信息', message: '请选择配件!' });
      }
      // 编辑部分
      let json = {
        STORAGE_NAME: this.tablelistfirst.STORAGE_NAME,
        STORAGE_POSITION_CODE: this.tablelistfirst.STORAGE_POSITION_CODE,
        UNIT_CODE: this.tablelistsecond[0].UNIT_CODE,
        UNIT_NAME: this.tablelistsecond[0].UNIT_NAME,
        COST_PRICE: this.tablelistsecond[0].COST_PRICE,
        COST_AMOUNT: this.tablelistsecond[0].COST_PRICE * this.fromSubmitdata.LOSS_QUANTITY,
        statusitem: 'A',
        IS_NEGATIVE: this.tablelistfirst.IS_NEGATIVE
      };
      let formdata = Object.assign({}, this.fromSubmitdata, json);
      if (formdata.PART_NO === '' || formdata.STORAGE_CODE === '') {
        return this.$notify.error({ title: '提示信息', message: '请选择配件!' });
      }
      if (formdata.LOSS_QUANTITY > this.tablelistsecond[0].USEABLE_STOCK) {
        return this.$notify.error({ title: '提示信息', message: '配件数量不可以大于可用库存' });
      }
      this.$emit('change', formdata);
      // if (formdata.LOSS_QUANTITY > this.tablelistsecond[0].USEABLE_STOCK) {
      //   this.$confirm('是否记录缺料明细？', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   })
      //     .then(async () => {
      //       //记录缺料信息
      //       let res = await lackInventory({
      //         storageCode: this.fromSubmitdata.STORAGE_CODE,
      //         lossNo: this.lossNo,
      //         storagePositionCode: this.tablelistfirst.STORAGE_POSITION_CODE,
      //         partNo: this.fromSubmitdata.PART_NO,
      //         partName: this.fromSubmitdata.PART_NAME,
      //         inOutType: '12171007',
      //         shortType: '12141004', //缺料类型
      //         shortQuantity: this.fromSubmitdata.LOSS_QUANTITY,
      //         closeStatus: '10041002'
      //       });
      //       if ((res.resultCode = '200')) {
      //         this.$notify.success({ title: '提示信息', message: '记录缺料信息成功!' });
      //         if (this.tablelistfirst.IS_NEGATIVE === '10041002') {
      //           return this.$notify.error({ title: '提示信息', message: '当前仓库不允许负库存!' });
      //         } else {
      //           this.$emit('change', formdata);
      //         }
      //       } else {
      //         return this.$notify.error({ title: '提示信息', message: '记录缺料信息失败!' });
      //       }
      //     })
      //     .catch(() => {
      //       //this.$emit('change', formdata);
      //     });
      // } else {
      //   this.$emit('change', formdata);
      // }
    }
  }
};
</script>
